package com.fenghui.doubantop.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 抽象的解析工具类
 */
public abstract class ParseUtil<T> {

    protected abstract void extractInfo(Element child, T item);

    protected abstract Element getElement(Document document);

    protected abstract boolean isIgnoredTag(Element element);

    protected abstract T createItem();

    public List<T> parse(String url) {
        Document document = null;
        try {
            document = Jsoup.connect(url).get();
        } catch (IOException e) {
            // 记录详细的错误日志
            System.err.println("Error occurred while connecting to URL: " + url + ", Error: " + e.getMessage());
            return new ArrayList<>();
        }

        Element element = getElement(document);
        List<T> items = new ArrayList<>();
        for (Element child : element.children()) {
            if (!isIgnoredTag(child)) {
                T item = createItem();
                extractInfo(child, item);
                items.add(item);
            }
        }
        return items;
    }
}

